import React from 'react';
import {Table, Icon} from 'antd';
import styles from './index.less';

class UploadView extends React.Component {
  constructor(props){
    super(props);
    this.columns = [
      {
        title: '序号',
        align:'center',
        dataIndex: 'no',
        className:'zzx-upload-file-no',
        render: (text, record, index) => {
          return <div>{index + 1}</div>
        },
      },
      {
        title: '类别',
        dataIndex: 'cate',
        className:'zzx-upload-file-cate',
      },
      {
        title: '预览',
        dataIndex: 'thumb',
        className: 'zzx-upload-file-thumb',
        render: (text) => {
          if (text) {
            const {type, data} = text;
            switch (type) {
              case 'image':
                return (
                  <div onClick={this.handlePreview(text)}>
                    <img src={data} width={28} height={28} alt='' />
                  </div>
                );
              default:
                break;
            }
          }
          return <Icon type='file' style={{fontSize: 28}} />
        },
      },
      {
        title: '资料名称',
        dataIndex: 'alias',
        className: 'zzx-upload-file-name',
        render: (text) => {
          return <span title={text}>{text}</span>;
        },
      },
      {
        title: '操作',
        dataIndex: 'action',
        className:'zzx-upload-file-action',
        render: (_, record) => (
          <a href="#" onClick={e => this.handleDelete(e, record)}>
            <Icon type="delete" />
          </a>
        ),
      },
    ];
  }
  state = {
    dataSource: [],
  }
  componentWillMount() {
    const {dataSource = []} = this.props;
    this.setState({dataSource: this.getDataSource(dataSource)})
  }
  componentWillReceiveProps(nextProps) {
    const {dataSource = []} = nextProps;
    this.setState({dataSource: this.getDataSource(dataSource)})
  }
  getDataSource = (dataSource = []) => {
    return dataSource.map(item => {
      const newItem = item;
      newItem.selected = false;
      return newItem;
    });
  }
  handlePreview = (recordValue) => {
    const {data} = recordValue;
    return () => {
      window.open(data,'_blank');
    }
  }
  handleDelete = (e, record) => {
    e.preventDefault();
    const {onDelete} = this.props;
    if (onDelete) {
      onDelete(record);
    }
  }

  render() {
    const {dataSource=[], pagination=false} = this.state;
    return (
      <div className={styles.zzUpload}>
        {(dataSource.length) ?
          (
            <div>
              <Table
                size='small'
                pagination={pagination}
                columns={this.columns}
                dataSource={dataSource}
                bordered
                style={{display: dataSource.length ? '' : 'none'}}
                rowKey={record => record.id}
              />
            </div>
          )
          : ''
        }
      </div>
    )
  }

}

export default UploadView;